import React, {Component} from 'react';
import {Card, Descriptions, Tag, Image, message} from 'antd';
import {ArrowLeftOutlined} from "@ant-design/icons";
import './book_detail.less';
import {reqBookDetail} from '../../../api/book';
import moment from 'moment';

// 首页
export default class BookDetail extends Component {
  state = {
    data: {}
  }

  // 返回上一页
  backClick = () => {
    this.props.history.goBack(); // 返回，页面会刷新
    // this.props.history.go(-1);
  }
  // 图书详情
  getBookDetail = async (id, data = {}) => {
    try {
      const {data: result} = await reqBookDetail(id, data);
      this.setState({data: result})
    } catch (e) {
      console.log(e);
      message.error(e.data.name || e.data.message)
    }
  }

  componentDidMount() {
    this.getBookDetail(this.props.match.params.id, {fields: 'download_time'});
  }

  render() { // render会执行2次，默认渲染1次，state修改时一次
    const {data} = this.state;
    const title = (
      <span>
        <ArrowLeftOutlined style={{cursor: 'pointer'}} onClick={this.backClick}/>
        <h1 className='detail-title'>
          图书详情页
        </h1>
      </span>
    )

    return (
      <Card title={title}>
        {
          Object.keys(data).length > 0 ? <Descriptions column={1} bordered>
            {Object.keys(data.book_infos).map(i =>
              <Descriptions.Item label={i} key={i}>
                {data.book_infos[i]}
              </Descriptions.Item>)
            }
            <Descriptions label='图片封面'>
              <Image src={data.image} width={100}/>
            </Descriptions>
            <Descriptions label='关于作者'>
              {data.about_author}
            </Descriptions>
            <Descriptions label='摘要'>
              {data.abstract}
            </Descriptions>
            <Descriptions label='标签'>
              {
                data.tags.map(item => <Tag key={item}>{item}</Tag>)
              }
            </Descriptions>
            <Descriptions label='更新时间'>{moment(data.update_time).format('YYYY年MM月DD日 HH:mm:ss')}</Descriptions>
            <Descriptions label='下载时间'>{moment(data.download_time).format('YYYY年MM月DD日 HH:mm:ss')}</Descriptions>
          </Descriptions> : null
        }
      </Card>
    )
  }
}

